// import Vue from 'vue'
import axios from 'axios'
// import router from '@/router'
import qs from 'qs'
import merge from 'lodash/merge'
// import { clearLoginInfo } from '@/utils'

const http = axios.create({
  timeout: 1000 * 30,
  withCredentials: true,
  headers: {
    'Content-Type': 'application/json; charset=utf-8'
  }
})

/**
 * 请求拦截
 */
http.interceptors.request.use(config => {
  // config.headers['token'] = Vue.cookie.get('token') // 请求头带上token
  config.headers['token'] = sessionStorage.getItem('token')
  return config
}, error => {
  return Promise.reject(error)
})

/**
 * 响应拦截
 */
http.interceptors.response.use(response => {
  if (response.data && response.data.code === 401) { // 401, token失效
    // clearLoginInfo()
    // router.push({ name: 'login' })
  }
  if (response.data && response.data.code === 404) { // 404, 接口不存在
    // router.push({ name: '404' })
  }
  if (response.data && response.data.code === 502) { // 502, 网关错误
    // router.push({ name: '502' })
  }
  return response
}, error => {
  return Promise.reject(error)
})

/**
 * 请求地址处理
 * @param {*} actionName action方法名称
 */
http.adornUrl = (actionName, demoUrl = null) => {
  // 非生产环境 && 开启代理, 接口前缀统一使用[/proxyApi/]前缀做代理拦截!
  return '/proxyApi/' + actionName
}

/**
 * get请求参数处理
 * @param {*} params 参数对象
 * @param {*} openDefultParams 是否开启默认参数?
 */
http.adornParams = (params = {}, openDefultParams = true) => {
  var defaults = {
    't': new Date().getTime()
  }
  // console.log(merge(params))
  params = openDefultParams ? merge(defaults, params) : params
  return qs.stringify(params, { indices: false })
}

/**
 * post请求数据处理
 * @param {*} data 数据对象
 * @param {*} openDefultdata 是否开启默认数据?
 * @param {*} contentType 数据格式
 *  json: 'application/json; charset=utf-8'
 *  form: 'application/x-www-form-urlencoded; charset=utf-8'
 */
http.adornData = (data = {}, openDefultdata = true, contentType = 'json') => {
  if (contentType === 'file') {
    return data
  }
  var defaults = {
    't': new Date().getTime()
  }
  data = openDefultdata ? merge(defaults, data) : data
  return contentType === 'json' ? JSON.stringify(data) : qs.stringify(data, { indices: false })
}

// request 再次封装
http.request = (url, data = {}, method = 'get', contentType = 'json', download = 'NO') => {
  return new Promise(function (resolve, reject) {
    let header = {
      'Content-Type': 'application/json; charset=utf-8'
    }
    if (contentType === 'form') {
      header['Content-Type'] = 'application/x-www-form-urlencoded; charset=utf-8'
    } else if (contentType === 'file') {
      header['Content-Type'] = 'multipart/form-data'
    }
    if (method.toUpperCase() === 'GET' || method.toUpperCase() === 'DELETE') {
      let formUrl = url ? http.adornUrl(url) : http.adornUrl()
      let formData = data ? http.adornParams(data) : ''
      formUrl += '?' + formData
      http({
        url: formUrl,
        header: header,
        method: method,
        params: '',
        responseType: download === 'YES' ? 'arraybuffer' : 'json'
      }).then(res => {
        console.log('\n')
        console.log('%cURL: ', 'color:blue', http.adornUrl(url))
        console.log('%c请求: ', 'color:blue', formData)
        console.log('%c响应: ', 'color:blue', res)
        if (download === 'YES') {
          resolve(res)
        } else {
          resolve(res.data)
        }
      }).catch(res => {
        console.log('\n')
        console.log('%c发生服务器错误: ', 'color:red', res)
      })
    } else {
      http({
        url: url ? http.adornUrl(url) : http.adornUrl(),
        header: header,
        method: method,
        data: data ? http.adornData(data, !Array.isArray(data), contentType) : http.adornData(),
        responseType: download === 'YES' ? 'arraybuffer' : 'json'
      }).then(res => {
        console.log('\n')
        console.log('%cURL: ', 'color:blue', http.adornUrl(url))
        console.log('%c请求: ', 'color:blue', http.adornData(data))
        console.log('%c响应: ', 'color:blue', res)
        if (download === 'YES') {
          resolve(res)
        } else {
          resolve(res.data)
        }
      }).catch(res => {
        console.log('\n')
        console.log('%c发生服务器错误: ', 'color:red', res)
        reject(res)
      })
    }
  })
}

export default http
